package main

import (
	"context"
	"flag"
	"fmt"
	"ginfast/api/system"
	"ginfast/api/system/model"
	"ginfast/middleware"
	"ginfast/pkg/dao"
	"ginfast/util"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

// newApp 创建gin对象
func newApp() *gin.Engine {
	// gin.SetMode(gin.ReleaseMode)
	app := gin.Default()
	app.Use(gin.Logger()) // 日志
	// r.Use(middleware.LoadTLS()) // https
	app.Use(middleware.Cors()) // 跨域
	r := app.Group("/api/v1/system")
	system.Routers(r)
	return app
}

var (
	menuconfigure = flag.String("mc", "../../conf/menu.json", "请输入配置文件")
)

func configureMenu(jsonfile string) error {
	var menus []model.SysMenu
	if err := util.JSONFile(jsonfile, &menus); err != nil {
		return err
	}
	return dao.DbCreate(&menus)
}

func main() {
	flag.Parse()
	db, err := dao.NewGormV2("mysql", "root:123456@tcp(172.16.50.219:3306)/test?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		log.Fatalln(err)
	}
	db.AutoMigrate(system.Models()...)
	if dao.DbCount(&model.SysMenu{}, nil) < 1 {
		configureMenu(*menuconfigure)
	}
	r := newApp()
	address := fmt.Sprintf(":%d", 8080)
	s := &http.Server{
		Addr:           address,
		Handler:        r,
		ReadTimeout:    120 * time.Second,
		WriteTimeout:   120 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	go func() {
		// service connections
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")
	gctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	s.Shutdown(gctx)
	// catching gctx.Done(). timeout of 5 seconds.
	<-gctx.Done()
}
